package io.github.thesixonenine.chapter1.sync;

import java.util.concurrent.TimeUnit;

/**
 * @author Simple
 * @version 1.0
 * @date 2021/01/03 15:30
 * @since 1.0
 */
public class Start {
    public static void main(String[] args) throws InterruptedException {
        while (true) {
            nosafe();
        }
    }

    /**
     * 可能出现的结果:
     * <p>
     * 由第一个人计算: 4
     * 由第四个人计算: 3
     * 由第五个人计算: 0
     * 由第二个人计算: 0
     * 由第三个人计算: 2
     * <p>
     * 解决办法: 在方法上加上synchronized关键字, 标记为同步方法
     *
     * @throws InterruptedException 打断异常
     */
    private static void nosafe() throws InterruptedException {
        // 初始化库存为5
        int initCount = 5;
        NoSafe noSafe = new NoSafe(initCount);
        // 5个人同时来买
        Thread thread1 = new Thread(noSafe, "第一个人");
        Thread thread2 = new Thread(noSafe, "第二个人");
        Thread thread3 = new Thread(noSafe, "第三个人");
        Thread thread4 = new Thread(noSafe, "第四个人");
        Thread thread5 = new Thread(noSafe, "第五个人");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        TimeUnit.SECONDS.sleep(1L);
        int count = noSafe.getCount();
        System.out.println("剩余库存: " + count);
    }

    private synchronized
    static void safe() throws InterruptedException {
        // 初始化库存为5
        int initCount = 5;
        NoSafe noSafe = new NoSafe(initCount);
        // 5个人同时来买
        Thread thread1 = new Thread(noSafe, "第一个人");
        Thread thread2 = new Thread(noSafe, "第二个人");
        Thread thread3 = new Thread(noSafe, "第三个人");
        Thread thread4 = new Thread(noSafe, "第四个人");
        Thread thread5 = new Thread(noSafe, "第五个人");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        TimeUnit.SECONDS.sleep(1L);
        int count = noSafe.getCount();
        System.out.println("剩余库存: " + count);
    }
}
